package com.yxjx.duoxue.activities;

import java.io.IOException;
import java.util.ArrayList;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.TextareaTag;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.TextExtractingVisitor;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.customview.YxDetailedInfoView;
import com.yxjx.duoxue.utils.UIHelper;

import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Html.TagHandler;
import android.util.Log;

public class RichTextHelper {
	
	
	private ArrayList<Integer> mItemTypes = new ArrayList<Integer>();
	private ArrayList<Object> mData = new ArrayList<Object>();
	
	public String getString() {
		return str;
	}
	
	/**
	 * Parsing data
	 * @param htmlString
	 */
	public void parseHtmlString(String htmlString) {
		
		if (UIHelper.isEmpty(htmlString)) {
			// skip the empty string case.
			htmlString = "暂未录入";
		}
		
		htmlString = "<p>" + htmlString + "</p>";
		Parser htmlParser = new Parser();
		try {
			htmlParser.setResource(htmlString);
			
			for (NodeIterator i = htmlParser.elements (); i.hasMoreNodes(); ) {  
                Node node = i.nextNode();  
                String text = node.toPlainTextString();
                NodeFilter filter = new TagNameFilter("IMG");    
				try {
					/** 得到过滤后的节点 **/
					Parser subParser = new Parser(node.toHtml());
					NodeList list = subParser.extractAllNodesThatMatch(filter);

					for (int c = 0; c < list.size(); c++) {
						ImageTag imageTag = (ImageTag) list.elementAt(c);
						/** 输出图片的链接Url **/
						System.out.println(imageTag.getImageURL());
						mData.add(imageTag.getImageURL());
		                mItemTypes.add(YxDetailedInfoView.TYPE_IMG);
					}
				} catch (ParserException e) {
					// do nothing
				}
//				text.replaceAll("\\s{1,}", "");
				text = text.trim();
				if (!UIHelper.isEmpty(text)) {
					text = text.replace("&nbsp;", "");
				}
				if (!UIHelper.isEmpty(text)) {
					mData.add(text);
					mItemTypes.add(YxDetailedInfoView.TYPE_TEXT);
				}
            }              
			
		} catch (ParserException e) {
			mData.add(htmlString);
			mItemTypes.add(YxDetailedInfoView.TYPE_TEXT);
			Log.d(Yx.TAG, "CCMM direct use htmlString = " + htmlString);
		}
		
	}
	
	/**
	 * Data type
	 * @return
	 */
	public ArrayList<Integer> getItemTypes() {
		return mItemTypes;
	}
	
	/**
	 * Data List
	 * @return
	 */
	public ArrayList<Object> getData() {
		return mData;
	}
	
	private String str = "";

}
